import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Search from '@/views/search'
import SearchList from '@/views/search/list'
import ProDetail from '@/views/prodetail'
import Pay from '@/views/pay'
import MyOrder from '@/views/myorder'
import NotFound from '@/views/NotFound'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'
Vue.use(VueRouter)
// 还有 createWebHashHistory 和 createMemoryHistory

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  // 动态路由传参，确认将来是哪个商品，路由参数中携带 id
  { path: '/prodetail/:id', component: ProDetail },
  { path: '/pay', component: Pay },
  { path: '/myorder', component: MyOrder },
  {
    path: '*',
    component: NotFound,
    redirect: '/home'
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})
// 全局导航守卫，所有页面都要经过放行才能进入
// to：到哪里去
// from：从哪里来
// next：是否放行
// 1.next（）直接去to的路径
// 2.next（路径） 拦截，拦截到next的路径
const authUrls = ['/pay', 'myorder']
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  const online = store.getters.online

  if (online) {
    next()
  } else {
    next('/login')
  }
})

export default router
